using System;
using FluentNHibernate;
using FluentNHibernate.Automapping;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Helpers.Builders;
using FluentNHibernate.Conventions.Instances;
using FluentNHibernate.Data;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using YourCuppa.Domain;

namespace YourCuppa.Services
{
    public class PrimaryKeyConvention
  : IIdConvention
    {
        public void Apply(IIdentityInstance instance)
        {
             
            instance.Column(instance.EntityType.Name + "Id");
        }
    }
    class ExampleAutomappingConfiguration : DefaultAutomappingConfiguration
    {
     

        public override bool IsId(Member member)
        {
            return member.Name == member.DeclaringType.Name + "Id";
        }
    }

    public class ShopService : IShopService
    {

        public void CreateShop()
        {
            throw new System.NotImplementedException();
        }

        public void RateShop()
        {
            throw new System.NotImplementedException();
        }


        static AutoPersistenceModel CreateAutomappings()
        {
            // This is the actual automapping - use AutoMap to start automapping,
            // then pick one of the static methods to specify what to map (in this case
            // all the classes in the assembly that contains Employee), and then either
            // use the Setup and Where methods to restrict that behaviour, or (preferably)
            // supply a configuration instance of your definition to control the automapper.
            return AutoMap.AssemblyOf<Shop>(new ExampleAutomappingConfiguration());

        }

        private static ISessionFactory CreateSessionFactory()
        {

        return    Fluently.Configure()
                   .Database
                   (
                   MsSqlConfiguration.MsSql2008
                       .ConnectionString(conn => conn.FromConnectionStringWithKey("YourCuppa"))
                              .ProxyFactoryFactory<NHibernate.ByteCode.Castle.ProxyFactoryFactory>())
                   .Mappings(m => m.AutoMappings.Add(CreateAutomappings()))
                        .ExposeConfiguration(BuildSchema)
                .BuildSessionFactory();

         
        }

        private static void BuildSchema(Configuration config)
        {
             
            new SchemaExport(config)
                .Create(false, true);
        }

        public void BuildSchema()
        {


            CreateSessionFactory();
        }
         
    }
}